package com.talkweb.historylib.dialog;

import com.talkweb.historylib.ResourceTable;
import com.talkweb.securitycamera.common.base.utils.ResourceHelper;
import com.talkweb.securitycamera.utils.TimeUtils;
import ohos.agp.components.*;
import ohos.agp.utils.TextTool;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;

/**
 * @author SUQI
 * @date 2021/2/5
 * @description 日期选择弹窗
 **/
public class SelectDateDialog extends BaseCommonDialog {
    private static final int VP_20 = 20;
    private Component mComponent;
    private DatePicker mDatePicker;
    private Button btnConfirm;
    private Button btnCancel;
    //用于比较的开始日期,截止时间大于等于开始日期
    private String startDate;
    private OnSelectedDateListener onSelectedDateListener;

    public SelectDateDialog(Context context, OnSelectedDateListener onSelectedDateListener) {
        super(context);
        this.onSelectedDateListener = onSelectedDateListener;
    }

    @Override
    protected boolean isBottomDialog() {
        return true;
    }

    @Override
    protected void initialize(Context context) {
        super.initialize(context);
        setCornerRadius(AttrHelper.vp2px(VP_20, context));
        setSize(ComponentContainer.LayoutConfig.MATCH_CONTENT, ComponentContainer.LayoutConfig.MATCH_CONTENT);
        mComponent = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_dialog_select_date, null, false);
        setContentCustomComponent(mComponent);
        initView();
    }

    private void initView() {
        mDatePicker = (DatePicker) mComponent.findComponentById(ResourceTable.Id_date_picker);
        btnConfirm = (Button) mComponent.findComponentById(ResourceTable.Id_dialog_confirm);
        btnCancel = (Button) mComponent.findComponentById(ResourceTable.Id_dialog_cancel);
        btnCancel.setClickedListener(component -> hide());
        btnConfirm.setClickedListener(component -> {
            if (!TextTool.isNullOrEmpty(startDate)) {
                long endTime = TimeUtils.string2Millis(String.format("%d-%d-%d", mDatePicker.getYear(), mDatePicker.getMonth(), mDatePicker.getDayOfMonth()), TimeUtils.FORMAT_PATTERN);
                if (TimeUtils.string2Millis(startDate, TimeUtils.FORMAT_PATTERN) > endTime) {
                    new ToastDialog(getContext()).setText(ResourceHelper.getString(getContext(), ResourceTable.String_select_time_must_than_start_time)).setDuration(2000).show();
                    return;
                }
            }
            hide();
            if (onSelectedDateListener != null) {
                onSelectedDateListener.onResult(mDatePicker.getYear(), mDatePicker.getMonth(), mDatePicker.getDayOfMonth());
            }
        });
    }

    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }

    public interface OnSelectedDateListener {
        void onResult(int year, int month, int day);
    }
}
